/*
 * 
 * Version 1.00
 * 
 * Created on 2007-6-4
 * Encoding GB2312
 */
package net.comm.file.service.impl;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;

import net.comm.page.PageCtr;
import net.comm.param.service.impl.SequenceMgr;
import net.comm.pic.ConvertVideo;
import net.comm.util.DatetimeUtil;
import net.comm.common.Decode;
import net.comm.common.Fileload;
import net.comm.common.GlbFinal;
import net.comm.common.PatternMa;
import net.comm.common.ReturnMessage;
import net.comm.common.common;

import net.comm.file.bean.BaseFiles;
import net.comm.file.db.DbFilesService;
import net.comm.file.db.FilesServiceSqlMysql;
import net.comm.file.web.form.FilesForm;
import net.comm.util.DbcpPool;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;
import org.dom4j.io.SAXReader;
import org.sakaiproject.db.impl.BasicSqlService;


/**
 *
 * @author hcgong(hcgong@sina.com)
 * @version 1.0
 * @date 2007-6-4
 */
public class FilesServiceImpl {

	static Logger logger = Logger.getLogger(FilesServiceImpl.class.getName());

	/**
	 * 
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#list(net.swift.module.other.ExaQueryBean, net.swift.common.ReturnMessage)
	 */
	public List list(FilesForm theForm,  ReturnMessage msg) 
	{
		List list = null;

		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			FilesServiceSqlMysql servSql = new FilesServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();

			/*
			 * 获得查询SQL语句
			 */
			String sql = servSql.getCountSql1();

			/**
			 * 根据SQL执行结果计算分页相关信息
			 */
			PageCtr page = theForm.getPage();
			page.setTotalNum(bSqlServ.dbCount(cn, sql, null));
			page.caculate();

			//取得FORM中传入的查询参数
			Object[] fields = new Object[3];
			
			fields[1] = page.getPos()-1;
			fields[2] = page.getPageSize();
			
			sql = servSql.getRecbyPageSql();

			list = bSqlServ.dbRead(cn, sql, fields, new DbFilesService());
			
			
		    DbcpPool.returnConnection(cn);
		    
		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
			
		} finally {
			DbcpPool.returnConnection(cn);
		}		
		
		return list;
	}
	/**
	 * 
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#list(net.swift.module.other.ExaQueryBean, net.swift.common.ReturnMessage)
	 */
	public List adlist(FilesForm theForm,  ReturnMessage msg) 
	{
		List list = new Vector();

		Connection cn = null;
		Statement stmt=null;
		ResultSet rs=null;
		try
		{
			cn = DbcpPool.getConnection();
			
			FilesServiceSqlMysql servSql = new FilesServiceSqlMysql();
			
			StringBuffer sb = new StringBuffer(" where 1=1 ");


			//查询记录数
			stmt = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			String sql = servSql.getCountSql1();

			logger.debug(sql+sb.toString());
			rs=stmt.executeQuery(sql+sb.toString());
			int nRows = 0;
			if (rs.next())
	           nRows = rs.getInt("COUNT");
			else
			{
	            rs.close();
	            stmt.close();
	            DbcpPool.returnConnection(cn);
			    return list;
			}
			/**
			 * 根据SQL执行结果计算分页相关信息
			 */
			PageCtr page = theForm.getPage();
			page.setTotalNum(nRows);
			page.caculate();

			sb.append(" limit ");
			sb.append(page.getPos()-1);
			sb.append(", ");
			sb.append(page.getPageSize());
			
			 //取记录
			 sql = servSql.getRecSql();
			 logger.debug(sql+sb.toString());
			 DbFilesService dbuser = new DbFilesService();
			 
			 rs=stmt.executeQuery(sql+sb.toString());
			 while (rs.next())
			 {
				try
				{
					Object obj = dbuser.readSqlResultRecord(rs);
					if (obj != null) list.add(obj);
				}
				catch (Throwable t)
				{
					logger.error(t.getMessage());
				}		
			 }
			 rs.close();
			 stmt.close();
		     DbcpPool.returnConnection(cn);

		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				DbcpPool.returnConnection(cn);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}			
	    }finally {
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}			
			DbcpPool.returnConnection(cn);
		}		
		return list;
	}	
	/**
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#get(net.swift.db.tab_paramnostro, net.swift.common.ReturnMessage)
	 */
	public void get(FilesForm theForm, ReturnMessage msg) 
	{

		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			get(cn, theForm, msg);
			
			DbcpPool.closeTran(cn);			
			DbcpPool.returnConnection(cn);
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}				
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}

	/**
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#get(net.swift.db.tab_paramnostro, net.swift.common.ReturnMessage)
	 */
	public void get(Connection cn,FilesForm theForm, ReturnMessage msg) 
	{

		try
		{
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = theForm.getF_ID();
						
			FilesServiceSqlMysql servSql = new FilesServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getbykeySql();
						
			List list = bSqlServ.dbRead(cn, sql, fields, new DbFilesService());
			
			if(list.size() == 0){
				common.setAppFailMsg(msg , " 取文件失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			BaseFiles base = (BaseFiles)list.get(0);
			
			BeanUtils.copyProperties(theForm, base);
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about files" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}				
		} finally {
		}
		
		return ;
	}
	/**
	 * 增加文件 
	 */
	public void add(FilesForm theForm, ReturnMessage msg) 
	{

		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			DbcpPool.beginTran(cn);

			add(cn, theForm, msg);

			DbcpPool.commitTran(cn);
			DbcpPool.closeTran(cn);			
			DbcpPool.returnConnection(cn);
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about files" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}				
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}	
	/**
	 * 增加文件 
	 */
	public void add(Connection cn, FilesForm theForm, ReturnMessage msg) 
	{

		try
		{

			FilesServiceSqlMysql servSql = new FilesServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();

	    	String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); 
	    	//  path==/D:/eclipse3.2workspaces/E_learning/WebRoot/WEB-INF/classes/
	    	if(path.indexOf("WEB-INF/")>0){
	    		path = path.substring(1,path.indexOf("WEB-INF/"));
	    	}
	    	path = path.replaceAll("/", "\\\\");
			
	    	Fileload fileload = new Fileload(path);

	    	String foldername = theForm.getFolder();
	    	if(foldername.equals("")){
	    		
				foldername = fileload.newFolder(path,"files\\");
	    	}else{
	    		
				foldername = fileload.chkFolderExist(path,foldername);
	    	}
	    	
			//
			String  savefile = "";
			
			//取得上传文件1
			FormFile file 	= theForm.getFormFile(); 
			if(file == null || file.getFileName().equals(""))
	        {
        		common.setAppFailMsg(msg , " 上传文件不存在！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;	        		
	        }
			float len = file.getFileSize()/(1024*1024);
        	if(len > 1024 ){
				common.setAppFailMsg(msg , 
						"当前单个文件大小为" + len +"M，允许最大上传文件大小为1024M");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;	        		
        	}				
        	//
			theForm.setF_ID(SequenceMgr.generateSeq( GlbFinal.SEQ_INITDATE,GlbFinal.SEQ_FILEID));			
			
			String rex = file.getFileName().toLowerCase();

			int dot = rex.lastIndexOf(".");
			rex = rex.substring(dot);
			String picrex = "(\\.jpg|\\.png|\\.gif|\\.jpeg)";
			String videorex = "(\\.avi)";
			
			savefile = GlbFinal.SEQ_FILEID + theForm.getF_ID() + DatetimeUtil.getTime() + rex;
			
			boolean ret = false;
			//上传图片
			if(PatternMa.matchingText(picrex, rex)){
				if(theForm.getF_Zip() == GlbFinal.ZIP_135_110){
					
					ret = fileload.addfile(file,savefile,0,135,110);
				}else if(theForm.getF_Zip() == GlbFinal.ZIP_200_200){
					
					ret = fileload.addfile(file,savefile,0,200,200);
				}else {
					//默认压缩到600
					ret = fileload.addfile(file,savefile,1,theForm.getImgWidth(),theForm.getImgHeight());
				}
			}else			
			//文件上传
			{		
	        	ret = fileload.addfile(file,savefile);
			}
			if(!ret){
	    		common.setAppFailMsg(msg , " 上传文件失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;	        		
        	}					
			//处理上传视频
			if(PatternMa.matchingText(videorex, rex)){ 
				
    			//执行视频转换
    			ConvertVideo cvideo = new ConvertVideo(path + foldername, path + GlbFinal.VIDEOPRG_PATH);
    			if(cvideo.process(savefile)){

    				savefile = savefile.substring(0, savefile.lastIndexOf(".")) + ".flv";
    			}else{
    	    		common.setAppFailMsg(msg , " 视频转换失败！");
    				DbcpPool.rollBackTran(cn);
    				DbcpPool.closeTran(cn);
    				DbcpPool.returnConnection(cn);
    				return;	     				
    			}
			}
			
        	theForm.setF_size(file.getFileSize());
			theForm.setFolder(foldername.replaceAll("\\\\", "/"));//保存WEB查看格式);
			theForm.setF_name(savefile);
			theForm.setF_Type(rex);
			
			//插入记录
			Object[] fields = new Object[10];
			
			fields[0] = theForm.getF_ID();
			fields[1] = theForm.getF_info();
			fields[2] = theForm.getFolder();
			fields[3] = theForm.getF_name();
			fields[4] = theForm.getF_File2();
			fields[5] = 1;
			fields[6] = theForm.getF_Type();
			fields[7] = theForm.getF_Zip();
			fields[8] = theForm.getF_size();
			fields[9] = DatetimeUtil.getDatetime();
						
			String sql = servSql.getInsertSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , "文件记录插入失败，请检查！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}

			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about files" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}				
		} finally {
		}
		
		return ;
	}	
	/**
	 * 删除一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void delete(FilesForm theForm, ReturnMessage msg) 
	{
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			DbcpPool.beginTran(cn);

			delete(cn, theForm, msg);
			
			DbcpPool.commitTran(cn);
			DbcpPool.closeTran(cn);
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about files" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}
	/**
	 * 删除一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void delete(Connection cn, FilesForm theForm, ReturnMessage msg) 
	{
		
		try
		{

			FilesServiceSqlMysql servSql = new FilesServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			//读取文件信息
			Object[] fields = new Object[1];
			fields[0] = theForm.getF_ID();

			String sql = servSql.getbykeySql();
			
			List list = bSqlServ.dbRead(cn, sql, fields, new DbFilesService());
			
			if(list.size() == 0){
				common.setAppFailMsg(msg , " 取文件记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			BaseFiles base = (BaseFiles)list.get(0);
			
			//删除物理文件
	    	String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath(); 
			String filepath = path + base.getFolder() + base.getF_name();
			
			filepath.replaceAll("/", "\\\\");
			
	        File fF = new File(filepath);   
       		if(fF != null){
       			fF.delete();
       		}

//       		int dot = base.getF_name().lastIndexOf(".");
//       		String rex = base.getF_name().substring(dot);
//			String picrex = "(\\.jpg|\\.png|\\.gif|\\.jpeg)";
//			PatternMa.matchingText(picrex, rex))
			
       		//删除压缩的小照片
			if(base.getF_Zip() == GlbFinal.ZIP_135_110)	{
				filepath = path + base.getFolder() + "zip" + base.getF_name();
				
				filepath.replaceAll("/", "\\\\");
		        fF = new File(filepath);   
	       		if(fF != null){
	       			fF.delete();
	       		}			
			}
       		//删除附件文件2
			
			//删除数据库记录
			sql = servSql.getDeleteSql();
			
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 删除记录失败，请检查！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;
			}
			
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about files" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
		}
		
		return ;
	}	
	/**
	 * 更新照片
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void update(Connection cn,FilesForm theForm, ReturnMessage msg) 
	{
		
		if(theForm.getF_ID() != 0){
			
			delete(cn, theForm, msg);
		}		
		add(cn,theForm, msg);
	}

}
